<template>
  <div class="app-container">
    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="default"
          @click="handleAdd"
        >
          {{ $t("form.evaluation.addPermissionGroup") }}
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="evalWeightGroupList"
    >
      <el-table-column
        :label="$t('form.evaluation.weightGroupName')"
        align="center"
        prop="name"
      />
      <el-table-column
        align="center"
        v-for="role in evalRoleList"
        :key="role.id"
        :label="role.name"
      >
        <template #default="scope">{{ scope.row.weightList.find(item => item.roleId === role.id)?.weight }}%</template>
      </el-table-column>
      <el-table-column
        :label="$t('form.evaluation.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="ele-Edit"
            @click="handleUpdate(scope.row)"
          >
            {{ $t("form.evaluation.modify") }}
          </el-button>
          <el-button
            link
            type="primary"
            icon="ele-Delete"
            @click="handleDelete(scope.row)"
          >
            {{ $t("form.evaluation.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改权重组对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
    >
      <el-row>
        <el-col :span="6">
          <span>{{ $t("form.evaluation.roleSelection") }}</span>
          <el-checkbox-group
            v-model="selectRoleIds"
            size="default"
            class="role-checkbox-group"
            @change="handleRoleChange"
          >
            <div
              v-for="role in evalRoleList"
              :key="role.id"
            >
              <el-checkbox :value="role.id">
                {{ role.name }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-col>
        <el-col :span="18">
          <el-form
            ref="evalWeightGroupRef"
            :model="form"
            :rules="rules"
            label-position="top"
            label-width="180px"
          >
            <el-form-item
              :label="$t('form.evaluation.weightGroupName')"
              prop="name"
            >
              <el-input
                v-model="form.name"
                maxlength="100"
                clearable
                :placeholder="$t('form.evaluation.enterWeightGroupName')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('form.evaluation.weightSettings')"
              prop="weightList"
            >
              <el-row
                class="w100"
                align="middle"
              >
                <el-col
                  :span="6"
                  v-for="wg in form.weightList"
                  :key="wg.roleId"
                >
                  <div class="weight-item-wrap">
                    <el-tooltip
                      :content="getEvalRoleName(wg.roleId)"
                      placement="top"
                    >
                      <span class="weight-item-name">{{ getEvalRoleName(wg.roleId)!.substring(0, 10) }}</span>
                    </el-tooltip>
                    <div>
                      <el-input-number
                        v-model="wg.weight"
                        :min="1"
                        :max="100"
                        clearable
                        @change="handleWeightChange(wg)"
                        controls-position="right"
                        size="small"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col
                  :span="6"
                  v-if="totalWeight"
                >
                  <div class="text-success title-medium">= {{ totalWeight }}%</div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            :loading="buttonLoading"
            type="primary"
            @click="submitForm"
          >
            {{ $t("form.evaluation.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ $t("form.evaluation.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EvalWeightGroup" lang="ts">
import {
  addEvalWeightGroup,
  delEvalWeightGroup,
  EvalWeightGroup,
  getEvalWeightGroup,
  listEvalWeightGroup,
  updateEvalWeightGroup,
  WeightItem
} from "@/api/evaluation/weightGroup";
import { computed, ref } from "vue";
import { MessageUtil } from "@/utils/messageUtil";
import { ElMessageBox } from "element-plus";
import { resetFormRef } from "@/utils/tduck";
import type { FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { ResultData } from "@/api/types";
import { evaluationHook } from "@/views/form/evaluation/useEvaluation";
import { i18n } from "@/i18n";

const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const title = ref("");

const selectRoleIds = ref([]);

const route = useRoute();

const form = ref<EvalWeightGroup>({ name: "", weightList: [] });
const queryParams = ref({
  formKey: ""
});
const rules = ref({
  formKey: [
    {
      required: true,
      message: i18n.global.t("form.evaluation.formKeyCannotBeEmpty"),
      trigger: "blur"
    }
  ],
  name: [
    {
      required: true,
      message: i18n.global.t("form.evaluation.enterName"),
      trigger: "blur"
    }
  ]
});

const handleRoleChange = (value: number[]) => {
  if (!form.value.weightList) {
    form.value.weightList = [];
  }
  if (value) {
    form.value.weightList = value.map(item => {
      return {
        roleId: item,
        weight: undefined
      };
    });
  }
};

const { evalRoleList, evalWeightGroupList } = evaluationHook;

/** 查询权重组列表 */
const getList = () => {
  loading.value = true;
  queryParams.value.formKey = route.query.key as string;
  listEvalWeightGroup(queryParams.value).then(response => {
    evalWeightGroupList.value = response.data;
    loading.value = false;
  });
};

const getEvalRoleName = (id: number) => {
  const role = evalRoleList.value.find(item => item.id === id);
  return role ? role.name : "";
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

const evalWeightGroupRef = ref<FormInstance | null>(null);

// 表单重置
const reset = () => {
  selectRoleIds.value = [];
  form.value = {
    id: undefined,
    name: "",
    weightList: []
  };
  resetFormRef(evalWeightGroupRef);
};

/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true;
  reset();
  title.value = i18n.global.t("form.evaluation.addPermissionGroup");
};

/** 修改按钮操作 */
const handleUpdate = (row: EvalWeightGroup) => {
  loading.value = true;
  getEvalWeightGroup(row.id).then((response: ResultData<EvalWeightGroup>) => {
    loading.value = false;
    open.value = true;
    reset();
    form.value = response.data;
    selectRoleIds.value = form.value.weightList.map(item => item.roleId);
    title.value = i18n.global.t("form.evaluation.modifyWeightGroup");
  });
};
const totalWeight = computed(() => {
  return form.value.weightList.reduce((prev, cur) => {
    return prev + (cur.weight || 0);
  }, 0);
});

const handleWeightChange = (item: WeightItem) => {
  // 检查当前值+上其他值是否超过了100 如果超过了100 那么把当前的值设置为100-其他值 如果其他值已经为100 那么他是0
  const otherWeight = totalWeight.value - (item.weight || 0);
  if (totalWeight.value > 100) {
    item.weight = 100 - otherWeight;
  }
};

/** 提交按钮 */
const submitForm = () => {
  if (totalWeight.value !== 100) {
    MessageUtil.error(i18n.global.t("form.evaluation.weightSumMustBe100"));
    return;
  }
  form.value.formKey = route.query.key as string;
  evalWeightGroupRef.value!.validate((valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateEvalWeightGroup(form.value)
          .then(() => {
            MessageUtil.success(i18n.global.t("common.updateSuccess"));
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addEvalWeightGroup(form.value)
          .then(() => {
            MessageUtil.success(i18n.global.t("common.addSuccess"));
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = (row: EvalWeightGroup) => {
  ElMessageBox.confirm(i18n.global.t("form.evaluation.confirmDeleteWeightGroupNumber", { name: row.name }))
    .then(function () {
      loading.value = true;
      return delEvalWeightGroup(row.id);
    })
    .then(() => {
      loading.value = true;
      getList();
      MessageUtil.success(i18n.global.t("common.deleteSuccess"));
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
};

getList();
</script>
<style lang="scss" scoped>
:deep(.role-checkbox-group .el-checkbox__label) {
  display: inline-block;
  width: 150px;
  overflow: hidden;
}

.weight-item-wrap {
  background-color: var(--el-bg-color-overlay);
}
</style>
